package com.service.lotterySystem.controller;

import com.service.config.DistinctQa;
import com.service.config.annotation.Log;
import com.service.config.enums.BusinessType;
import com.service.config.enums.OperatorType;
import com.service.config.utils.*;
import com.service.lotterySystem.dto.LQaDto;
import com.service.lotterySystem.dto.OperateUserInfoDto;
import com.service.lotterySystem.dto.QueryQaInfoDto;
import com.service.lotterySystem.entity.LQa;
import com.service.lotterySystem.entity.OperateInfo;
import com.service.lotterySystem.enums.RoleTypeEnum;
import com.service.lotterySystem.service.LQaService;
import com.service.lotterySystem.service.OperateUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.Map;

import static com.service.config.constant.Constant.*;

/**
 * 问卷调查，用户留资(LQa)表控制层
 *
 * @author makejava
 * @since 2022-03-02 15:49:40
 */

@Api(value = "问卷调查接口", tags = "问卷调查接口")
@RestController
@RequestMapping("lQa")
@Slf4j
public class LQaController {
    /**
     * 服务对象
     */
    @Resource
    private LQaService lQaService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OperateUserService operateUserService;

    /**
     * 用户调查留资保存信息
     * @param
     * @return
     */
    @RequestMapping(value = "/addQaInfo", method = RequestMethod.POST)
    @ApiOperation(value = "新增活动")
    @ResponseBody
    @DistinctQa
    @Log(isSaveRequestData = true,businessType = BusinessType.INSERT,operatorType = OperatorType.MANAGE)
    public Result addQaInfo(@RequestBody LQaDto lQaDto) {
        try {
            LQa lQa = ModelMapperUtil.strictMap(lQaDto, LQa.class);
            OperateInfo operateInfo = operateUserService.queryById(lQaDto.getToken());
            lQa.setRegion(operateInfo.getRegion());
            lQa.setId(IdUtil.getStringId());
            lQa.setoId(lQaDto.getToken());
            lQa.setAddTime(new Date());
            lQaService.insert(lQa);
            return Result.ok();
        }catch (Exception e) {
            redisUtil.delete(lQaDto.getTelPhone());
            return Result.failure("请重新提交");
        }
    }
    /**
     * 用户调查留资保存信息
     * @param
     * @return
     */
    @RequestMapping(value = "/findQaInfo", method = RequestMethod.GET)
    @ApiOperation(value = "查询服务咨询/超级管理员查询查询普通管理员的服务咨询信息")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result findQaInfo(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                             @RequestParam(value = "card") @ApiParam("card:0--用户侧 1--运营侧")Integer card,
                             @RequestParam(value = "ordinary",required = false) @ApiParam("普通管理员id")String ordinary,
                             @RequestParam("page") @ApiParam("页码") Integer page,@RequestParam("pageSize") @ApiParam("一页的条数") Integer pageSize) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) {
                if (card != 1) {
                    return Result.failure("无权限操作");
                }
                try {
                    OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId), OperateUserInfoDto.class);
                    if (!userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                        Map<String,Object> map = lQaService.findQaInfo(userId,page,pageSize);
                        return Result.ok().setData(map);
                    }
                    if (StringUtils.isNotEmpty(ordinary)) {
                        Map<String,Object> map = lQaService.findQaInfo(ordinary,page,pageSize);
                        return Result.ok().setData(map);
                    }
                    Map<String,Object> map = lQaService.findQaInfo("",page,pageSize);
                    return Result.ok().setData(map);
                } catch (Exception e) {
                    log.error("findQaInfo: "+e.getMessage());
                    return Result.failure(USERNAME_Off_SITE,usernameOffSite);
                }
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     *生成验证码
     */
   // @ApiOperation(value = "生成验证码（暂时不用）")
    @RequestMapping(value = "/captcha" ,method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
        String string = request.getSession().getAttribute("captcha").toString();
        redisUtil.set(string,1,string,1);
    }

    @ApiOperation(value = "导出服务咨询")
    @RequestMapping(value ="/exportQaInfo",method = RequestMethod.GET)
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.EXPORT,operatorType = OperatorType.MANAGE)
    public Result exportQaInfo(@RequestParam(value = "card") @ApiParam("card:0--用户侧 1--运营侧")Integer card,
                               @RequestParam(value = "ordinary",required = false) @ApiParam("普通管理员id")String ordinary,
                               @RequestParam(value = "startDate",required = false) @ApiParam("开始日期")String startDate,
                               @RequestParam(value = "endDate",required = false) @ApiParam("结束日期")String endDate,
                               @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                if (card != 1) {
                    return Result.failure("无权限操作");
                }
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId), OperateUserInfoDto.class);
                if (userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    if (StringUtils.isNotEmpty(ordinary)) {
                        return lQaService.exportQaInfo(userId,userDto.getOperateName(),startDate,endDate);
                    }
                    return lQaService.exportQaInfo("",userDto.getOperateName(),startDate,endDate);
                }
                return lQaService.exportQaInfo(userId,userDto.getOperateName(), startDate, endDate);
            } else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    /**
     * 高级查询
     * @param
     * @return
     */
    @RequestMapping(value = "/queryInfoByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "高级查询")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result queryInfoByCondition(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                             @RequestParam(value = "card") @ApiParam("card:0--用户侧 1--运营侧")Integer card,
                             @RequestParam(value = "condition") @ApiParam("筛选内容")String condition,
                             @RequestParam("page") @ApiParam("页码") Integer page,@RequestParam("pageSize") @ApiParam("一页的条数") Integer pageSize) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) {
                if (card != 1) {
                    return Result.failure("无权限操作");
                }
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId), OperateUserInfoDto.class);
                if (userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    Map<String,Object> map = lQaService.queryInfoByCondition("",page,pageSize,condition);
                    return Result.ok().setData(map);
                }
                Map<String,Object> map = lQaService.queryInfoByCondition(userId,page,pageSize,condition);
                return Result.ok().setData(map);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 高级查询
     * @param
     * @return
     */
    @RequestMapping(value = "/queryInfoByTimeOrRegion", method = RequestMethod.POST)
    @ApiOperation(value = "管理员高级查询")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result queryInfoByTimeOrRegion(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                          @RequestBody  QueryQaInfoDto queryQaInfoDto,
                                          @RequestParam(value = "card") @ApiParam("card:0--用户侧 1--运营侧")Integer card,
                                          @RequestParam("page") @ApiParam("页码") Integer page,@RequestParam("pageSize") @ApiParam("一页的条数") Integer pageSize) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) {
                if (card != 1) {
                    return Result.failure("无权限操作");
                }
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId), OperateUserInfoDto.class);
                if (userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    Map<String,Object> map = lQaService.queryInfoByTimeOrRegion("",page,pageSize,queryQaInfoDto);
                    return Result.ok().setData(map);
                }
                Map<String,Object> map = lQaService.queryInfoByTimeOrRegion(userId,page,pageSize,queryQaInfoDto);
                return Result.ok().setData(map);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
}
